package com.wwj.service.impl;

import com.wwj.common.constant.MessageConstant;
import com.wwj.common.constant.PasswordConstant;
import com.wwj.common.constant.StatusConstant;
import com.wwj.mapper.UserMapper;
import com.wwj.pojo.dto.UserLoginDTO;
import com.wwj.pojo.entity.Employee;
import com.wwj.pojo.entity.User;
import com.wwj.service.UserService;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.security.auth.login.AccountLockedException;
import javax.security.auth.login.AccountNotFoundException;
import java.time.LocalDateTime;

@Service
public class UserServiceImpl implements UserService {


    @Resource
    private UserMapper userMapper;

    private static final String salt="cLo8QmTG";

    //用户注册
    @Override
    public void register(User user) {
        System.out.println("当前UserServiceImpl线程的id"+Thread.currentThread().getId());

        String username=user.getUsername();
        Integer count = userMapper.selectUser(username);
        if(count > 0){
            throw new RuntimeException(MessageConstant.USERNAME_FOUND);
        }
        String md5password=salt.charAt(0)+ user.getPassword() +salt.charAt(5);
        String password= DigestUtils.md5DigestAsHex(md5password.getBytes());
        System.out.println(password);
        user.setPassword(password);
        user.setCreateTime(LocalDateTime.now());
        userMapper.register(user);
    }

    //用户登录
    @Override
    public User login(UserLoginDTO userLoginDTO) {
        String username = userLoginDTO.getUsername();
        String password = userLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        User user = userMapper.selectByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (user == null) {
            //账号不存在
            throw new RuntimeException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        // TODO 后期需要进行md5加密，然后再进行比对
        String md5password=salt.charAt(0)+password+salt.charAt(5);
        password=DigestUtils.md5DigestAsHex(md5password.getBytes());
        System.out.println(password);
        if (!password.equals(user.getPassword())) {
            //密码错误
            throw new RuntimeException(MessageConstant.PASSWORD_ERROR);
        }


        //3、返回实体对象
        return user;
    }

    //个人中心查询
    @Override
    public User UserCenter(String userName) {
        User user = userMapper.selectByUsername(userName);
        return user;
    }

    //修改用户
    @Override
    public User updateUser(User user) {
        String password=user.getPassword();
        String md5password=salt.charAt(0)+password+salt.charAt(5);
        password=DigestUtils.md5DigestAsHex(md5password.getBytes());
        System.out.println(password);
        user.setPassword(password);
        userMapper.updateUser(user);
        User user1 = userMapper.selectByUsername(user.getUsername());
        return user1;
    }
}
